package org.dna.mybatis.criteria;

/**
 * Simple math expression for <, >, <= , >=, ==
 *
 * @author andrea
 */
public class SimpleExpression<T> implements Criterion {

    public enum Operator {

        LT("<"), GT(">"), LE("<="), GE(">="), EQ("==");
        private final String m_op;

        Operator(String op) {
            m_op = op;
        }

        @Override
        public String toString() {
            return m_op;
        }
    };
    private String m_propName;
    private String m_columnName = null;
    private Operator m_operator;
    private T m_value;

    SimpleExpression(String propertyName, Operator op, T value) {
        m_propName = propertyName;
        m_operator = op;
        m_value = value;
    }

    public String getSql() {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        if (m_columnName == null) { //property not bound
            sb.append("< not bound:").append(m_propName).append(">");
        } else {
            sb.append(m_columnName);
        }
        sb.append(" ").append(m_operator).append(" ").append(m_value).append(")");
        return sb.toString();
    }

    public boolean verify(Criteria criteria) {
        return criteria.hasProperty(m_propName) && criteria.checkType(m_propName, m_value.getClass());
    }
    
    public void bind(Criteria crit) throws CriteriaException {
        m_columnName = crit.toColumnName(m_propName);
    }
}
